package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.SysMgtErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ViewpointErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSFields;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.TopFlag;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.ViewpointStatusType;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.BrokerBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.CommentSaveResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.SelfMediaDavList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.SelfMediaListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointCommentDavResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointContent;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointDavList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointDetailDavList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointPublicData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointTagListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.CommentReplayForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.CommentReplayIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.SelfMediaListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewPointIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewPointTopForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointCommentForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointDetailListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointSaveForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointTagForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointTagIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointTagSortForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointTagUpdateForm;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.SysContants;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerManager;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointMsg;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointReply;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointTag;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointDetailDavView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointReplyView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointTagView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointView;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointMsgService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointReplyService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointTagService;
import com.cloudbroker.bcs.platform.dav.middle.util.PositionStrUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.SearchUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.ViewpointMsgFormatUtil;

@Service
public class BrokerBizServiceImpl implements BrokerBizService {
    
    @Resource
    private ViewpointMsgService viewpointMsgService;
    @Resource
    private ViewpointReplyService viewpointReplyService;
    @Resource
    private ViewpointTagService viewpointTagService;
    @Resource
    private BrokerService brokerService;
    @Resource
    private BrokerManagerService brokerManagerService;
    @Resource
    private TenantService tenantService;
    
    public static final Integer VIEWPOINT_TYPE = 2;
    
    @Override
    public ViewpointTagListResult funcBrokerTagList(HSBCPSVO param) {
        ViewpointTagListResult ret = new ViewpointTagListResult();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        List<ViewpointTagView> list = viewpointTagService.queryByBrokerId(broker_id);
        
        if (null != list && list.size() > 0) {
            ret.newDataList().addAll(list);
        } else {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_TAG_LIST,
                    ViewpointTagListResult.class);
        }
        return VOUtil.setSuccessResult(ret);
    }
    
    @Override
    public SelfMediaDavList funcSelfMediaList(SelfMediaListForm form) {
        SelfMediaDavList result_list = new SelfMediaDavList();
        String key_word = form.getKey_word();
        Integer page_no = Integer.parseInt(form.getPage_no());
        Integer page_size = Integer.parseInt(form.getPage_count());
        List<Map<String, Object>> list = SearchUtil.getInstance().getSelfMediaList(key_word, page_no, page_size,
                "send_time", "DESC", "1");
        if (null != list && list.size() > 0) {
            List<SelfMediaListData> selfMediaList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                SelfMediaListData data = new SelfMediaListData();
                data.setBroker_avatar(ValueUtil.getString(map.get("broker_avatar")));
                data.setBroker_name(ValueUtil.getString(map.get("broker_name")));
                data.setViewpoint_id(ValueUtil.getLong(map.get("id")));
                data.setViewpoint_abstract(ValueUtil.getString(map.get("label")));
                data.setViewpoint_tag_name(ValueUtil.getString(map.get("tag_name")));
                data.setViewpoint_img_audio(ValueUtil.getString(map.get("img_audio")));
                data.setPosition_str(ValueUtil.getString(map.get("position_str_long")));
                String content = ValueUtil.getString(map.get("content"));
                data.setViewpoint_content(ViewpointMsgFormatUtil.parseContext(content));
                data.setViewpoint_tag_id(ValueUtil.getLong(map.get("tag_id")));
                data.setBroker_id(ValueUtil.getLong(map.get("broker_id")));
                data.setDate(changeDate(ValueUtil.getString(map.get("send_time"))));
                data.setViewpoint_title(ValueUtil.getString(map.get("viewpoint_title")));
                selfMediaList.add(data);
            }
            Map<String, Object> totalmap = list.get(0);
            result_list.setTotal_item_num(ValueUtil.getString(totalmap.get("total")));
            result_list.newDataList().addAll(selfMediaList);
            return VOUtil.setSuccessResult(result_list);
        } else {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_HISTORY_RECORD, SelfMediaDavList.class);
        }
    }
    
    private String changeDate(String time) {
        StringBuilder sb = new StringBuilder();
        sb.append(time.substring(0, 4)).append("-").append(time.substring(4, 6)).append("-")
                .append(time.substring(6, 8)).append(" ").append(time.substring(8, 10)).append(":")
                .append(time.substring(10, 12)).append(":").append(time.substring(12, 14));
        return sb.toString();
    }
    
    @Override
    public ViewpointDavList funcViewpointListByDav(ViewpointListForm param) {
        String viewpoint_tag_name = param.getViewpoint_tag_name();
        String position_str = param.getPosition_str();
        int request_num = ValueUtil.getInt(param.getRequest_num(), ConfigValues.getRequestNum());
        String status = param.getViewpoint_status();
        String charge_flag = param.getCharge_flag();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        
        List<ViewpointView> msgs = this.viewpointMsgService.queryViewpointList(broker_id, status,
                viewpoint_tag_name, charge_flag, request_num, position_str);
        ViewpointDavList ret = new ViewpointDavList();
        ret.newDataList().addAll(msgs);
        
        return VOUtil.setSuccessResult(ret);
    }
    
    @Override
    public ViewpointContent funcViewpointContent(ViewPointIdForm param) {
        ViewpointMsg vp = viewpointMsgService.getViewpointByID(param.getViewpoint_id());
        if (vp == null) {
            return VOUtil.genErrorResult(SysMgtErr.NO_SUCH_VIEWPOINT_ID, ViewpointContent.class);
        }
        ViewpointContent result = new ViewpointContent();
        result.setViewpoint_content(vp.getViewpoint_content());
        result.setViewpoint_tag(vp.getViewpoint_tag());
        result.setPrice(vp.getPrice());
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO brokerViewpointSave(ViewpointSaveForm param) {
        Integer tenantId = HSBCPSBizDataContext.getTenantId();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        //校验标签所属
        String viewpoint_tag_id = param.getViewpoint_tag_id();
        ViewpointTag vt = this.viewpointTagService.get(viewpoint_tag_id);
        if (null == vt || !broker_id.equals(vt.getBroker_id())) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_TAG);
        }
        //校验观点内容
        String viewpoint_content = param.getViewpoint_content();
        try {
            JSONObject contentJson = JSON.parseObject(viewpoint_content);
            String content = contentJson.getString("content");
            if (StringUtil.isBlank(content)) {
                return VOUtil.genErrorResultVo(ViewpointErr.VIEWPOINT_CONTENT_NOT_BLANK);
            }
        } catch (Exception e) {
            return VOUtil.genErrorResultVo(BasicErrorCodes.PARAM_ERROR);
        }
        String viewpoint_abstract = param.getViewpoint_abstract();
        if (viewpoint_abstract != null && viewpoint_abstract.length() > 2000) {
            viewpoint_abstract = viewpoint_abstract.substring(0, 2000);
        }
        String viewpoint_img_audio = param.getViewpoint_img_audio();
        Integer viewpoint_status = Integer.parseInt(param.getViewpoint_status());
        Integer price = Integer.parseInt(param.getPrice());
        String viewpoint_id = param.getViewpoint_id();
        String type = param.getViewpoint_public_flag();
        Tenant tenant = tenantService.get(ValueUtil.getString(tenantId));
        String checkFlag = "";   //是否需要审核，0-不需要，1-需要
        String checkStatus = "";  //如果需要审核则默认为0，不需要则默认为1,0-未通过审核，1-通过审核
        if ("1".equals(type)){
            checkFlag = tenant.getSelf_media_check_flag();
        }else {
            checkFlag = tenant.getViewpoint_check_flag();
        }
        if (StringUtil.isBlank(checkFlag) || "0".equals(checkFlag)){
            checkStatus = "1";
        } else{
            checkStatus = "0";
        }
        // 修改
        Date send_time = null;
        if (!StringUtil.isBlank(param.getCreate_time())) {
            try {
                send_time = DateTimeUtil.toDate(param.getCreate_time(), DateTimeUtil.FORMAT_YYYYMMDDHHMMSS);
            } catch (ParseException e) {
                send_time = new Date();
                e.printStackTrace();
            }
        } else {
            send_time = new Date();
        }
        if (!StringUtil.isBlank(viewpoint_id)) {
            ViewpointMsg msg = viewpointMsgService.get(viewpoint_id);
            if (null == msg || !broker_id.equals(msg.getBroker_id())) {
                return VOUtil.genErrorResultVo(SysMgtErr.NO_SUCH_VIEWPOINT_ID);
            }
            Integer status = msg.getViewpoint_status();
            if (ViewpointStatusType.DEL.getVal() == status) {
                return VOUtil.genErrorResultVo(SysMgtErr.NO_SUCH_VIEWPOINT_ID);
            }
            //修改
            msg.setViewpoint_tag(vt.getViewpoint_tag_id());
            msg.setViewpoint_tag_name(vt.getTag_name());
            if (ViewpointStatusType.SEND.getVal() == status) {
                msg.setViewpoint_status(status);
            } else {
                msg.setViewpoint_status(viewpoint_status);
                if (viewpoint_status == 1) {
                    msg.setSend_time(send_time);
                }
            }
            msg.setViewpoint_abstract(viewpoint_abstract);
            msg.setPrice(new BigDecimal(price));
            msg.setViewpoint_content(viewpoint_content);
            msg.setViewpoint_img_audio(viewpoint_img_audio);
            String position_str = PositionStrUtil.getPositionStr();
            msg.setPosition_str(position_str);
            msg.setUpdate_time(send_time);
            msg.setViewpoint_public_status(checkStatus);
            msg.setViewpoint_type(type);
            viewpointMsgService.update(msg);
            SearchUtil.getInstance().updateToSearch(msg, ValueUtil.getInt(type), checkStatus);
        } else {
            // 保存
            ViewpointMsg msg = new ViewpointMsg();
            msg.setBroker_id(broker_id);
            msg.setViewpoint_content(viewpoint_content);
            msg.setViewpoint_abstract(viewpoint_abstract);
            msg.setViewpoint_img_audio(viewpoint_img_audio);
            msg.setViewpoint_tag(vt.getViewpoint_tag_id());
            msg.setViewpoint_tag_name(vt.getTag_name());
            msg.setComment_num(0);
            msg.setReward_num(0);
            msg.setUpvote_num(0);
            msg.setIs_top(0);
            msg.setPrice(new BigDecimal(price));
            msg.setTotal_income(new BigDecimal(0));
            msg.setViewpoint_status(viewpoint_status);
            if (ViewpointStatusType.SEND.getVal() == viewpoint_status) {
                msg.setSend_time(send_time);
            }
            String position_str = PositionStrUtil.getPositionStr();
            msg.setPosition_str(position_str);
            msg.setUpdate_time(send_time);
            msg.setViewpoint_public_status(checkStatus);
            msg.setViewpoint_type(type);
            viewpointMsgService.save(msg);
            
            Broker broker = brokerService.get(String.valueOf(msg.getBroker_id()));
            
            //已发布的才保存到搜索引擎
            if (ViewpointStatusType.SEND.getVal() == viewpoint_status) {
                SearchUtil.getInstance().addToSearch(msg, broker, ValueUtil.getInt(type), checkStatus);
            }
            
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO brokerViewpointDel(ViewPointIdForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String viewpoint_id = param.getViewpoint_id();
        ViewpointMsg msg = viewpointMsgService.get(viewpoint_id);
        if (null != msg && broker_id.equals(msg.getBroker_id())) {
            int viewpoint_status = msg.getViewpoint_status();
            //已发布的修改为删除状态
            if (ViewpointStatusType.SEND.getVal() == viewpoint_status) {
                msg.setViewpoint_status(ViewpointStatusType.DEL.getVal());
                viewpointMsgService.update(msg);
                //更新搜索引擎
                SearchUtil.getInstance().deleteToSearch(VIEWPOINT_TYPE, viewpoint_id);
            } else if (ViewpointStatusType.DRAFT.getVal() == viewpoint_status) {
                //草稿箱的观点直接删除
                viewpointMsgService.delete(viewpoint_id);
                //删除对应搜索引擎
                SearchUtil.getInstance().deleteToSearch(VIEWPOINT_TYPE, viewpoint_id);
            } else {
                //不允许删除的状态
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_ID);
            }
        } else {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_ID);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public ViewpointCommentDavResult viewpointCommentList(ViewpointCommentForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String viewpoint_id = param.getViewpoint_id();
        String position_str = param.getPosition_str();
        
        ViewpointMsg msg = this.viewpointMsgService.getSendViewpointByID(viewpoint_id);
        if (null == msg || !broker_id.equals(msg.getBroker_id())) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_ID,
                    ViewpointCommentDavResult.class);
        }
        Integer request_num = ValueUtil.getInt(param.getRequest_num(), ConfigValues.getRequestNum());
        List<ViewpointReplyView> msgs = this.viewpointReplyService.queryViewpointReplyViews(viewpoint_id,
                request_num, position_str);
        
        ViewpointCommentDavResult result = new ViewpointCommentDavResult();
        result.newDataList().addAll(msgs);
        
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public CommentSaveResult commentReplaySave(CommentReplayForm param) {
        String viewpoint_id = param.getViewpoint_id();
        ViewpointMsg msg = this.viewpointMsgService.getSendViewpointByID(viewpoint_id);
        if (null == msg) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_ID, CommentSaveResult.class);
        }
        
        // 原评论ID
        String replay_from = param.getReplay_from();
        ViewpointReply from = viewpointReplyService.get(replay_from);
        if (from == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_COMM_ID,
                    CommentSaveResult.class);
        }
        String replay_content = param.getReplay_content();
        Broker broker = HSBCPSBizDataContext.getBroker();
        Long customer_id = broker.getBroker_id();
        String customer_name = broker.getBroker_name();
        
        ViewpointReply vr = new ViewpointReply();
        vr.setCustomer_id(customer_id);
        vr.setCustomer_name(customer_name);
        vr.setAvatar(broker.getBroker_avatar());
        vr.setReply_content(replay_content);
        vr.setReply_from(Long.parseLong(replay_from));
        vr.setViewpoint_id(Long.parseLong(viewpoint_id));
        vr.setPosition_str(PositionStrUtil.getPositionStr());
        vr.setBroker_flag(1);
        vr.setDelete_flag(0);
        viewpointReplyService.save(vr);
        
        msg.setUpdate_time(new Date());
        
        msg.setComment_num(msg.getComment_num() + 1);
        this.viewpointMsgService.update(msg);
        
        CommentSaveResult result = new CommentSaveResult();
        result.setComment_num(msg.getComment_num());
        
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public CommentSaveResult viewpointCommentDel(CommentReplayIdForm param) {
        String replay_id = param.getReplay_id();
        ViewpointReply vr = viewpointReplyService.get(replay_id);
        if (null == vr || vr.getDelete_flag() == 1) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_COMM_ID,
                    CommentSaveResult.class);
        }
        ViewpointMsg msg = this.viewpointMsgService.getSendViewpointByID(String.valueOf(vr.getViewpoint_id()));
        if (null != msg) {
            vr.setDelete_flag(1);
            viewpointReplyService.update(vr);
            msg.setComment_num(msg.getComment_num() - 1);
            this.viewpointMsgService.update(msg);
        } else {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_COMM_ID,
                    CommentSaveResult.class);
        }
        CommentSaveResult result = new CommentSaveResult();
        result.setComment_num(msg.getComment_num());
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO saveNewTag(ViewpointTagForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        Integer count = viewpointTagService.getByBrokerId(broker_id);
        Integer count1 = viewpointTagService.getByCountBrokerId(broker_id);
        Integer tag_num = ConfigValues.getDefineTagNum();
        if (tag_num <= count) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.DEFINE_TAG_LIMIT);
        }
        String tag_name = param.getViewpoint_tag_name().trim();
        ViewpointTag vr = viewpointTagService.getByName(broker_id, tag_name);
        if (null != vr) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.DEFINE_TAG_NAME_EXIST);
        } else {
            vr = new ViewpointTag();
            vr.setBroker_id(broker_id);
            vr.setTag_name(tag_name);
            if (count1 == null) {
                vr.setOrder_num(1);
            } else {
                vr.setOrder_num(count1 + 1);
            }
            vr.setTag_type(SysContants.DEFINE_TAG_TYPE);
            viewpointTagService.save(vr);
        }
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HSBCPSBackVO funcViewpointTop(ViewPointTopForm param) {
        String viewpoint_id = param.getViewpoint_id();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        ViewpointMsg msg = this.viewpointMsgService.getSendViewpointByID(viewpoint_id);
        if (msg == null || !msg.getBroker_id().equals(broker_id)) {
            return VOUtil.genErrorResult(SysMgtErr.NO_SUCH_VIEWPOINT_ID, HSBCPSBackVO.class);
        }
        if (msg.getViewpoint_status() != ViewpointStatusType.SEND.getVal()) {
            return VOUtil.genErrorResult(SysMgtErr.NO_TOP_DEL_VIEWPOINT, HSBCPSBackVO.class);
        }
        if (String.valueOf(TopFlag.TOP.getVal()).equals(param.getTop_flag())) {
            ViewpointMsg msg2 = new ViewpointMsg();
            msg2.setBroker_id(broker_id);
            msg2.setIs_top(TopFlag.TOP.getVal());
            List<ViewpointMsg> msgs = this.viewpointMsgService.query(msg2);
            if (msgs != null && msgs.size() > 0) {
                for (ViewpointMsg viewpointMsg : msgs) {
                    viewpointMsg.setIs_top(TopFlag.NOT_TOP.getVal());
                    viewpointMsgService.updateCAS(viewpointMsg);
                }
            }
        }
        msg.setIs_top(Integer.valueOf(param.getTop_flag()));
        viewpointMsgService.updateCAS(msg);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HSBCPSBackVO brokerTagDel(ViewpointTagIdForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String tag_id = param.getViewpoint_tag_id();
        
        //传0表示清空自定义标签
        if ("0".equals(tag_id)) {
            viewpointTagService.deleteAll(broker_id);
            return VOUtil.genSuccessResultVo();
        }
        ViewpointTag vt = viewpointTagService.get(tag_id);
        Integer list = viewpointTagService.getCountByBrokerId(broker_id);
        if (list > 1) {
            if (null != vt && broker_id.equals(vt.getBroker_id())) {
                viewpointTagService.delete(tag_id);
            } else {
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_TAG);
            }
        } else {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.LAST_TAG_NON_DELETABLE);
        }
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HSBCPSBackVO brokerViewpointClear(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        Integer status = ViewpointStatusType.DRAFT.getVal();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(HSBCPSFields.BROKER_ID, broker_id);
        params.put(HSBCPSFields.VIEWPOINT_STATUS, status);
        viewpointMsgService.changeAll(params);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public ViewpointPublicData funcViewpointPublicGet(HSBCPSVO param) {
        Integer tenantId = HSBCPSBizDataContext.getTenantId();
        Tenant tenant = tenantService.get(ValueUtil.getString(tenantId));
        ViewpointPublicData viewpointPublicData = new ViewpointPublicData();
        viewpointPublicData.setPublic_flag(tenant == null ? 0 : ValueUtil.getInt(tenant.getViewpoint_public_flag(),
                0));
        return VOUtil.setSuccessResult(viewpointPublicData);
    }
    
    @Override
    public ViewpointDetailDavList funcBrokerViewpointDetailList(ViewpointDetailListForm param) {
        Long userId = ValueUtil.getLong(param.getUser_id());
        ViewpointDetailDavList ret = new ViewpointDetailDavList();
        BrokerManager brokerManager = brokerManagerService.getByUserId(userId);
        if (null == brokerManager) {
            return VOUtil.setSuccessResult(ret);
        }
        Long brokerId = brokerManager.getBroker_id();
        Integer tenant_id = brokerManager.getTenant_id();
        int page_no = Integer.parseInt(param.getPage_no());
        int page_count = Integer.parseInt(param.getPage_count());
        Integer total_count = viewpointMsgService.countByBrokerId(brokerId, tenant_id);
        List<ViewpointDetailDavView> msgs = this.viewpointMsgService.queryViewpointDetailDavList(brokerId,
                (page_no - 1) * page_count, page_count);
        ret.newDataList().addAll(msgs);
        ret.setTotal_count(total_count);
        return VOUtil.setSuccessResult(ret);
    }
    
    @Override
    public HSBCPSBackVO updateNewTag(ViewpointTagUpdateForm param) {
        String tag_id = param.getViewpoint_tag_id();
        String tag_name = param.getViewpoint_tag_name().trim();
        ViewpointTag vr = viewpointTagService.get(tag_id);
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (vr == null) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_TAG);
        }
        if (broker_id.intValue() != vr.getBroker_id().intValue()) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.ClientErr.EXCEED_POWER);
        }
        ViewpointTag vrname = viewpointTagService.getByName(broker_id, tag_name);
        if (vrname != null) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.TAG_LIFE);
        }
        vr.setTag_name(tag_name);
        viewpointTagService.updateCAS(vr);
        
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HSBCPSBackVO sortNewTag(ViewpointTagSortForm param) {
        String tag_id = param.getTag_id_list();
        String[] tag_ids = tag_id.split(",");
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        for (int i = 0; i < tag_ids.length; i++) {
            ViewpointTag vr = viewpointTagService.get(tag_ids[i]);
            if (vr == null) {
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_TAG);
            }
            if (broker_id.intValue() != vr.getBroker_id().intValue()) {
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.ClientErr.EXCEED_POWER);
            }
            vr.setOrder_num(i + 1);
            viewpointTagService.updateCAS(vr);
        }
        return VOUtil.genSuccessResultVo();
    }
    
}
